# 官方网站：http://www.vnpy.cn
import logging
import os
import sys
import time

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtGui import QIcon
from os.path import abspath, dirname
import qdarkstyle
import mainwindow_ui as mainwindow
import globalvar
import configparser
from module_strategyprocess import *
import threading
import module_md
import module_td
import module_config
import module_kline
import webbrowser

globalvar._init()

sys.path.insert(0, abspath(dirname(abspath(__file__)) + '/..'))
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(os.path.split(rootPath)[0])
globalvar.ui = mainwindow.Ui_MainWindow()


def OnTimer_checkstranger():
    # 检查策略修改
    timer = threading.Timer(10, OnTimer_checkstranger)
    timer.start()


def CheckInvestor():
    try:
        # 实例化configParser对象
        config = configparser.ConfigParser()
        # read读取ini文件
        config.read('vnctptd.ini', encoding='utf-8')
        if config.getint('setting', 'investor') == 188075:
            print(
                "vnctptd.ini默认配置了公用账户，请尽快改用自己的账户\n上期官方模拟账户注册（需工作日白天访问，其余时间网站关闭）：http://www.simnow.com.cn\n实盘账户开立（A级期货公司，手续费条件非常优惠）：http://www.kaihucn.cn")
    except Exception as e:
        print("CheckInvestor Error:" + repr(e))


def InitReadConfig():
    globalvar.rc = module_config.MyReadConfig()
    globalvar.rc.ui = globalvar.ui
    try:
        globalvar.rc.generateinstrumentID()
    except Exception as e:
        print("generateinstrumentID Error:" + repr(e))
    globalvar.rc.readklineserversetting()
    globalvar.rc.readhistorystock()
    globalvar.rc.readoptionalstock()
    globalvar.ui.Function_Buttonclickh1()


def main():
    globalvar.currpath = os.path.abspath(os.path.dirname(__file__))
    logging.basicConfig(level=logging.DEBUG)
    app = QtWidgets.QApplication(sys.argv)
    window = globalvar.ui.VNMainWindow()
    globalvar.ui.setupUi(window)
    item = QtWidgets.QTableWidgetItem("1")
    item.setCheckState(QtCore.Qt.Unchecked)
    globalvar.ui.dockWidget1.raise_()
    tt = module_td.TDThread()
    tt.signal_td_tick.connect(globalvar.ui.callback_td_info)  # 进程连接回传到GUI的事件
    tt.start()
    tm = module_md.MDThread()
    tm.signal_md_tick.connect(globalvar.ui.callback_md_tick)  # 进程连接回传到GUI的事件
    tm.start()
    print(qdarkstyle.load_stylesheet_pyqt5())
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    # auto quit after 2s when testing on travis-ci
    if "--travis" in sys.argv:
        QtCore.QTimer.singleShot(2000, app.exit)
    OnTimer_checkstranger()
    window.setWindowTitle("VNPY官方[社区开源版] (http://www.vnpy.cn 探索更真实的量化交易世界)")
    window.setWindowIcon(QIcon('ico/vnpy.ico'))
    window.showMaximized()

    trynum = 0
    while not (globalvar.tdinit or globalvar.mdinit):
        time.sleep(0.1)
        trynum += 1
        if trynum > 200:
            # 如果超过200次无法登录行情服务器和交易服务器，则直接进入窗口界面
            break
    globalvar.vk = module_kline.MyKlineService(globalvar.ui.callback_kline)
    globalvar.vk.ui = globalvar.ui
    InitReadConfig()
    CheckInvestor()
    webbrowser.open('http://www.vnpy.cn/')
    app.exec_()
    os._exit(1)


if __name__ == "__main__":
    main()
